package pattern.singleton.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Spring中就是这种注册式单例
 * @author: jxj
 * @create: 2019-04-22
 **/
public class ContainerSingleton {
    //私有化构造方法
    private ContainerSingleton(){}
    private static Map<String,Object> ioc=new ConcurrentHashMap<String, Object>();
    public static Object getInstance(String className){
        synchronized (ioc){
            if(!ioc.containsKey(className)){
                Object obj=null;
                try {
                    obj=Class.forName(className).newInstance();
                    ioc.put(className,obj);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return obj;
            }else {
                return ioc.get(className);
            }
        }
    }
}
